package com.cyy.personinfowithkt

import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val data = getData()
        showPersonInfo(data!!)
    }

    private fun showPersonInfo(data: PersonInfo){
        val res = resources
        tv_name.text = String.format(res.getString(R.string.stu_name), data.stuName)
        tv_stuNum.text = String.format(res.getString(R.string.stu_num), data.stuNum)
        tv_sex.text = String.format(res.getString(R.string.sex), data.sex)
        tv_College.text = String.format(res.getString(R.string.college), data.college)
        tv_specialty.text = String.format(res.getString(R.string.specialty), data.specialty)
        loadPictureAsync(data.url){
            result -> img_head.setImageBitmap(result)
        }
    }

    private fun getData(): PersonInfo?{
        val data = PersonInfo(
                "Mr.chen",
                "man",
                201558080234,
                "College of Computer and Communication Engineering",
                "Network Engineering",
                "img/qrcode.png"
        )
        return data
    }

    private fun loadPictureAsync(url: String, callback: (Bitmap?)-> Unit){
        val task = LoadPictureTask(assets, callback)
        val result = task.execute(url)
    }

    private class LoadPictureTask
        constructor(val assets: AssetManager,
                    val callback: (Bitmap?) -> Unit): AsyncTask<String, Void, Bitmap>(){

        override fun doInBackground(vararg params: String?): Bitmap {
            val inStream = assets.open(params[0])
            val bitmap = BitmapFactory.decodeStream(inStream)
            inStream.close()
            return bitmap
        }

        override fun onPostExecute(result: Bitmap?) = callback(result)
    }
}
